import React, { ReactElement, useContext, useMemo } from 'react';
import { View, Text, Image } from 'react-native';

import styles from './style';
import Button from '../../../../components/Button';
import { Store } from '../../reducer';
import {
  CONTENT_WIDTH,
  EDIT_CONTENT_WIDTH,
  TITLE_WIDTH,
  EDIT_TITLE_WIDTH
} from '../../constant';
import { downloadSelected } from '../../../../constant/resource';
import { calBytes, selectDownloadParent } from '../../actions';
import { SortedDownloadVideoTasks } from '../../../../util/videoDownload/types';

export default (props: SortedDownloadVideoTasks): ReactElement => {
  const { parentId, parentTitle, totalSize, source } = props;

  const { state } = useContext(Store);
  const { isEdit, selectedPIds } = state;

  const isSelected = selectedPIds.includes(parentId);

  const contentWidth = isEdit ? EDIT_CONTENT_WIDTH : CONTENT_WIDTH;

  const titleWidth = isEdit ? EDIT_TITLE_WIDTH : TITLE_WIDTH;

  return useMemo(
    (): ReactElement => (
      <Button
        style={styles.container}
        onPress={(): void => {
          if (isEdit) {
            selectDownloadParent(parentId);
          }
        }}
      >
        {isEdit ? (
          <View style={styles.selectedBox}>
            {isSelected && (
              <Image style={styles.selectedIcon} source={downloadSelected} />
            )}
          </View>
        ) : null}
        <View style={[styles.content, { width: contentWidth }]}>
          <View style={styles.loadTitle}>
            <Text
              style={[styles.title, { width: titleWidth }]}
              numberOfLines={1}
            >
              {parentTitle}
            </Text>
            <Text style={styles.desc}>{calBytes(totalSize)}</Text>
          </View>
          <Text style={styles.source}>{source}</Text>
        </View>
      </Button>
    ),
    [
      contentWidth,
      isEdit,
      isSelected,
      parentId,
      parentTitle,
      source,
      titleWidth,
      totalSize
    ]
  );
};
